<?php

function smarty_modifier_var($value, $type, $config='') {
	global $db, $site;
	if ($type == 'Image') {
		$image = $db->fetchRow("SELECT id, filename, caption, description FROM cms_images WHERE id=? AND site_id=?", array($value, $site['id']));
		$value = '<img src="/images/' . ($config ? $config . '/' : '') . $image['id'] . '/'. $image['filename'] . '" alt="' . htmlentities($image['caption'], ENT_COMPAT, 'UTF-8') . '" title="' . htmlentities($image['description'], ENT_COMPAT, 'UTF-8') . '" />';
	}
	elseif ($type == 'ImageFolder') {
		$sort = in_array($config, array('filename', 'created', 'modified')) ? $config : 'id';
		$value = $db->fetchAll("SELECT id, filename, caption, description FROM cms_images WHERE folder_id=? AND site_id=? ORDER BY ?", array($value, $site['id'], $sort));
	}
	elseif ($type == 'File') {
		$file = $db->fetchRow("SELECT id, filename, caption, description FROM cms_files WHERE id=? AND site_id=?", array($value, $site['id']));
		$value = "/files/{$file['id']}/{$file['filename']}";
	}
	elseif ($type == 'FileFolder') {
		$sort = in_array($config, array('filename', 'created', 'modified')) ? $config : 'id';
		$value = $db->fetchAll("SELECT id, filename, caption, description FROM cms_files WHERE folder_id=? AND site_id=? ORDER BY ?", array($value, $site['id'], $sort));
		for($i=0;$i<count($value);$i++) {
			$value[$i]['path'] = "/files/{$value[$i]['id']}/{$value[$i]['filename']}";
		}
	}
	
	return $value;
}
$smarty->register_modifier('var', 'smarty_modifier_var');
